package com.atguigu.guli.service.base.exception;

import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice //异常处理的方法返回值作为json直接响应
//@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    //捕获最大异常
    @ExceptionHandler(value = Exception.class)
    public R exception(Exception e){
//        System.out.println(e.getClass().getName());
//        System.out.println(ExceptionUtils.getStackTrace(e));
        log.error(ExceptionUtils.getStackTrace(e));
        return R.error();
    }
    //单个异常的处理
    @ExceptionHandler(value = BadSqlGrammarException.class)
    public R exception(BadSqlGrammarException e){
//        System.out.println(ExceptionUtils.getStackTrace(e));
        log.error(ExceptionUtils.getStackTrace(e));
        return R.setResult(ResultCodeEnum.BAD_SQL_GRAMMAR);
    }
    @ExceptionHandler(value = HttpMessageNotWritableException.class)
    public R exception(HttpMessageNotWritableException e){
//        System.out.println(ExceptionUtils.getStackTrace(e));
        log.error(ExceptionUtils.getStackTrace(e));
        return R.setResult(ResultCodeEnum.JSON_PARSE_ERROR);
    }
}
